package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MyBatisUtils {
    //私有构造方法
    public MyBatisUtils() { }

    //声明工厂对象
    private static SqlSessionFactory sqlSessionFactory;

    //提供静态代码块,读取核心配置文件,并给工厂对象赋值
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //提供静态方法,获取SqlSession对象
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}
